package com.ukao.cashregister.ui.orderQuiry;


import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.gprinterio.GpDevice;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.OrderQuiryAdapter;
import com.ukao.cashregister.adapter.OrderTagAdapter;
import com.ukao.cashregister.base.IAdapter;
import com.ukao.cashregister.base.IPage;
import com.ukao.cashregister.base.MvpFragment;
import com.ukao.cashregister.base.PageWrapper;
import com.ukao.cashregister.bean.OrderQuiryTabeleBean;
import com.ukao.cashregister.bean.OrderQuriyStateBean;
import com.ukao.cashregister.bean.ReceiptBean;
import com.ukao.cashregister.dialog.CrippledDialogFragment;
import com.ukao.cashregister.dialog.DialogTool;
import com.ukao.cashregister.dialog.IntoBagDialogFragment;
import com.ukao.cashregister.dialog.TansNoDialogFragment;
import com.ukao.cashregister.eventbus.PayEvent;
import com.ukao.cashregister.listener.MyOnItemClickListener;
import com.ukao.cashregister.listener.MyTextWatcher;
import com.ukao.cashregister.listener.OnClickPopWindowListener;
import com.ukao.cashregister.listener.OnDialogSureClickListener;
import com.ukao.cashregister.listener.OnItemChildClickListener;
import com.ukao.cashregister.pesenter.OrderQuiryPesenter;
import com.ukao.cashregister.printer.PrintMiuiHelper;
import com.ukao.cashregister.printer.PrinterReceipt;
import com.ukao.cashregister.ui.MainActivity;
import com.ukao.cashregister.ui.stokin.GatheringFragment;
import com.ukao.cashregister.ui.stokin.StorageFragment;
import com.ukao.cashregister.utils.CheckUsbDeviceUtils;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.DensityUtils;
import com.ukao.cashregister.utils.MyDateUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.view.OrderQuiryView;
import com.ukao.cashregister.widget.SpinnerPopWindow;
import com.ukao.cashregister.widget.StateButton;
import com.ukao.cashregister.widget.StateImageView;
import com.ukao.cashregister.widget.TwinklingLayout;

import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.cashregister.R.id.fragment_arrive_shop_search1_edit;
import static com.ukao.cashregister.R.id.pay_layout;
import static com.ukao.cashregister.R.id.search_btn;
import static com.ukao.cashregister.utils.MyDateUtils.getTime;


public class OrderManageFragment extends MvpFragment<OrderQuiryPesenter> implements OrderQuiryView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(fragment_arrive_shop_search1_edit)
    EditText fragmentArriveShopSearch1Edit;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    @BindView(R.id.ordier_layout)
    RelativeLayout ordierLayout;
    @BindView(R.id.pay_tage)
    TextView payTage;
    @BindView(R.id.order_tage)
    TextView orderTage;
    @BindView(R.id.txt_time)
    TextView txtTime;
    @BindView(search_btn)
    Button searchBtn;
    @BindView(R.id.rfid_btn)
    StateImageView rfidBtn;
    @BindView(R.id.pay_layout)
    RelativeLayout payLayout;
    @BindView(R.id.twinkling_layout)
    TwinklingLayout twinklingLayout;
    @BindView(R.id.start_time)
    StateButton startBtn;
    @BindView(R.id.end_time)
    StateButton endBtn;


    public OrderQuiryTabeleBean.ListBean mitem;
    private String isOrderEnter;
    private List<OrderQuiryTabeleBean.ListBean> mrderQuiryData;
    private List<OrderQuriyStateBean> mPayData;
    private List<OrderQuriyStateBean> mAllData;
    private List<OrderQuriyStateBean> mTimeData;

    private Unbinder unbinder;
    private OrderQuiryAdapter mOrderQuiryAdapter;
    public String searchValue = "";
    private SpinnerPopWindow mSpinerPopWindow;
    private int popupWindowWith;
    private SpinnerPopWindow mOrderPopWindow;
    private SpinnerPopWindow mTimePopWindow;
    private OrderTagAdapter mOrderTimeAdapter;
    private PageWrapper mPageWrapper;
    private OrderTagAdapter mOrderPayAdapter;
    private OrderTagAdapter mOrderAllAdapter;
    private String[] timeStartDay = new String[4];
    private String timeType = "yyyy/MM/dd";
    public String statusVal = "";
    public String payStatus = "";
    public String invalidId;/*作废ID*/
    private boolean ismRemark;
    public String mstrRemark;/*备注的信息*/
    public boolean loadFinish;


    public static OrderManageFragment newInstance(String strorderNo, String isOrderEnter) {
        OrderManageFragment fragment = new OrderManageFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, strorderNo);
        args.putString(ARG_PARAM2, isOrderEnter);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            searchValue = getArguments().getString(ARG_PARAM1, "");
            isOrderEnter = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected OrderQuiryPesenter createPresenter() {
        return new OrderQuiryPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_order_quiry, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initListener();
        return view;
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (!loadFinish)
            twinklingLayout.startRefresh();

    }

    @Override
    protected void initView() {
        fragmentArriveShopSearch1Edit.setText("");
        initData();
        loadFinish = false;
        popupWindowWith = DensityUtils.getScreenW(activity) - DensityUtils.dip2px(_mActivity, 90);
       /*近来时间*/
        mOrderTimeAdapter = new OrderTagAdapter(activity, mTimeData);
        mTimePopWindow = new SpinnerPopWindow(activity, "创建时间");
        mTimePopWindow.setAdapter(mOrderTimeAdapter, 3);
        /*支付状态标签*/
        mOrderPayAdapter = new OrderTagAdapter(activity, mPayData);
        mSpinerPopWindow = new SpinnerPopWindow(activity, "支付状态");
        mSpinerPopWindow.setAdapter(mOrderPayAdapter, 0);
         /*全部状态标签*/
        mOrderAllAdapter = new OrderTagAdapter(activity, mAllData);
        mOrderPopWindow = new SpinnerPopWindow(activity, "订单状态");
        mOrderPopWindow.setAdapter(mOrderAllAdapter, 0);

        initLinearRecyclerView(recyclerView);
        /*列表*/

        mOrderQuiryAdapter = new OrderQuiryAdapter(activity, mrderQuiryData);
        recyclerView.setAdapter(mOrderQuiryAdapter);


        IPage page = new IPage() {
            @Override
            public void load(int geIndex, int pageSize) {
                if (CheckUtils.isNull(startBtn)) return;
                String stratday = startBtn.getText().toString();
                String endTime = endBtn.getText().toString();
                mvpPresenter.qrderQuiryData(_mActivity, geIndex, pageSize, stratday, endTime, payStatus, statusVal, searchValue);
            }
        };
        mPageWrapper = new PageWrapper<>(mIAdapter, page);


    }


    private void initData() {
        payStatus = "";
        statusVal = "";
        searchValue = "";
        mPayData = new ArrayList<>();
        mAllData = new ArrayList<>();
        mTimeData = new ArrayList<>();

        if (!CheckUtils.isEmpty(searchValue)) {
            fragmentArriveShopSearch1Edit.setText(searchValue);
        }
        mrderQuiryData = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                "yyyy/MM/dd");
        long currentTime = System.currentTimeMillis();
        Date Enddate = new Date(currentTime);
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DAY_OF_MONTH, -30);
        String startThirtiTime = simpleDateFormat.format(now.getTime());
        Date StarSeventdate = new Date(currentTime - 7 * 24 * 60 * 60 * 1000);
        String endTime = simpleDateFormat.format(Enddate);
        String startSevenTime = simpleDateFormat.format(StarSeventdate);
        timeStartDay[0] = "";
        timeStartDay[1] = endTime;
        timeStartDay[2] = startSevenTime;
        timeStartDay[3] = startThirtiTime;

        mPayData.add(new OrderQuriyStateBean("所有支付状态", ""));
        mPayData.add(new OrderQuriyStateBean("未支付", "0"));
        mPayData.add(new OrderQuriyStateBean("已支付", "1"));
        startBtn.setText(startThirtiTime);
        endBtn.setText(endTime);
        String[] orderTime = resources.getStringArray(R.array.orderTime);
        String[] orderName = resources.getStringArray(R.array.orderName);
        String[] orderNameId = resources.getStringArray(R.array.orderNameId);

        /*订单状态*/
        for (int i = 0; i < orderName.length; i++) {
            mAllData.add(new OrderQuriyStateBean(orderName[i], orderNameId[i]));
        }
        //时间
        for (int i = 0; i < orderTime.length; i++) {
            if (i == 0) {
                mTimeData.add(new OrderQuriyStateBean(orderTime[i], timeStartDay[i], ""));
            } else {
                mTimeData.add(new OrderQuriyStateBean(orderTime[i], timeStartDay[i], endTime));
            }

        }

    }

    @Override
    protected void initListener() {
        super.initListener();
        mSpinerPopWindow.setItemListener(mOnClickPopWindowListener);
        mOrderPopWindow.setItemListener(mOnClickPopWindowListener);
        mTimePopWindow.setItemListener(mOnClickPopWindowListener);
        mOrderQuiryAdapter.setOnItemClickListener(mOnItemClickListener);


        twinklingLayout.setOnRefreshListener(mRefreshListenerAdapter);
        mOrderPopWindow.setOnDismissListener(mOnDismissListener);
        mSpinerPopWindow.setOnDismissListener(mpayOnDismissListener);/*支付*/
        mOrderQuiryAdapter.setOnItemChildClickListener(mOnItemChildClick);
        fragmentArriveShopSearch1Edit.addTextChangedListener(mTextWatcher);
        fragmentArriveShopSearch1Edit.setOnEditorActionListener(mOnEditorAction);
    }


    TextView.OnEditorActionListener mOnEditorAction = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) {

                searchValueOrder();

            }
            return false;
        }
    };

    private TextWatcher mTextWatcher = new MyTextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            searchValue = s.toString();
        }
    };


    private OnItemChildClickListener mOnItemChildClick = new OnItemChildClickListener() {


        @Override
        public void onChildItemClick(int id, int pos) {
            mitem = mOrderQuiryAdapter.getItem(pos);
            if (mitem == null) return;
            switch (id) {
                case R.id.enter_potpocket_btn:
                    IntoBagDialogFragment mIntoBagDialog = IntoBagDialogFragment.newInstance(mitem.getId(), mitem.getOrderNo(), true);
                    mIntoBagDialog.show(getChildFragmentManager(), IntoBagDialogFragment.class.getName());
                    break;


                case R.id.transNo_btn:  /*工厂运单号*/
                    TansNoDialogFragment.createBuilder(getChildFragmentManager())
                            .title(getString(R.string.waybill_number))
                            .tansNo(mitem.getFactoryTransNo())
                            .mOnDialogSureClickListener(mOnDialogTansNoClickListener)
                            .show();
                    break;
                case R.id.storage_btn: /*入库*/

                    start(StorageFragment.newInstance(mitem.getOrderNo()));

                    break;
                case R.id.invalid_btn: /*作废*/
                    ismRemark = false;
                    invalidId = mitem.getId();
                    CrippledDialogFragment mInvalidDialog = new CrippledDialogFragment();
                    mInvalidDialog.setOnSureClickListener(mDialogListener);
                    mInvalidDialog.show(getChildFragmentManager(), CrippledDialogFragment.class.getName());
                    break;
                case R.id.remark_btn:/*备注*/
                    ismRemark = true;
                    invalidId = mitem.getId();
                    CrippledDialogFragment mRemarkDialog = new CrippledDialogFragment();
                    Bundle mBundle = new Bundle();
                    mBundle.putBoolean(ARG_PARAM1, true);
                    mBundle.putString(ARG_PARAM2, mitem.getRemark());
                    mRemarkDialog.setArguments(mBundle);
                    mRemarkDialog.setOnSureClickListener(mDialogListener);
                    mRemarkDialog.show(getChildFragmentManager(), CrippledDialogFragment.class.getName());

                    break;
                case R.id.gather_btn:/*收款*/
                    start(GatheringFragment.newInstance(mitem.getId() + "", "返回订单管理"));
                    break;
                case R.id.receipt_btn:/*小票*/
                    try {
                        if (CheckUtils.isMIUIDevices()/*&&CheckUtils.isHasPrinter(_mActivity)*/) {
                            mvpPresenter.printReceipt(_mActivity, mitem.getId());
                        } else {
                            if (CheckUsbDeviceUtils.isReceipt()) {/*小票*/
                                mvpPresenter.printReceipt(_mActivity, mitem.getId());
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

            }
        }
    };

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Subscribe
    public void onEvent(PayEvent event) {
        switch (event.getMessage()) {
            case PAY_SUCCEED:
                loadFinish = false;
                break;
        }

    }


    /**
     * 工厂运单号
     */
    private OnDialogSureClickListener mOnDialogTansNoClickListener = new OnDialogSureClickListener() {


        @Override
        public void onSureItemClick(Object message) {
            mvpPresenter.updateFactoryTransNo(mitem, (String) message);

        }
    };


    private OnDialogSureClickListener mDialogListener = new OnDialogSureClickListener() {


        @Override
        public void onSureItemClick(Object message) {

            if (ismRemark) {
                mstrRemark = (String) message;
                mvpPresenter.addRemark(_mActivity, invalidId, (String) message);
            } else {

                mvpPresenter.orderInfoDestroy(_mActivity, invalidId, (String) message);
            }


        }
    };


    private RefreshListenerAdapter mRefreshListenerAdapter = new RefreshListenerAdapter() {
        @Override
        public void onRefresh(TwinklingRefreshLayout refreshLayout) {
            super.onRefresh(refreshLayout);

            mPageWrapper.loadPage(true);
        }

        @Override
        public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
            super.onLoadMore(refreshLayout);

            mPageWrapper.loadPage(false);

        }
    };

    IAdapter mIAdapter = new IAdapter() {
        @Override
        public void setDataSource(List data, boolean isNextLoad) {

            mOrderQuiryAdapter.setDatas(data);
            twinklingLayout.finishRefreshing();
            twinklingLayout.setEnableLoadmore(isNextLoad);


        }

        @Override
        public void loadMoreFinish(List data, boolean isNextLoad) {
            mOrderQuiryAdapter.addDatas(data);
            twinklingLayout.finishLoadmore();
            twinklingLayout.setEnableLoadmore(isNextLoad);

        }
    };


    private PopupWindow.OnDismissListener mpayOnDismissListener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            payLayout.setBackgroundColor(getResource().getColor(R.color.pay_gay));
        }
    };

    private PopupWindow.OnDismissListener mOnDismissListener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {

            ordierLayout.setBackgroundColor(getResource().getColor(R.color.pay_gay));


        }
    };


    private OnClickPopWindowListener mOnClickPopWindowListener = new OnClickPopWindowListener() {
        @Override
        public void onSureItemClick(Object message) {
            OrderQuriyStateBean mOrderBean = (OrderQuriyStateBean) message;

//            if (selectpos==0){searchValue="";}/*如果是搜索所有*/
            if (mSpinerPopWindow.isShowing()) {
                searchValue = "";
                payLayout.setBackgroundColor(getResource().getColor(R.color.white));
                mSpinerPopWindow.dismiss();
                payTage.setText(mOrderBean.getPayStatus());
                payStatus = mOrderBean.getPayStatusId();
                twinklingLayout.startRefresh();

            }
            if (mOrderPopWindow.isShowing()) {
                searchValue = "";
                ordierLayout.setBackgroundColor(getResource().getColor(R.color.white));
                mOrderPopWindow.dismiss();
                orderTage.setText(mOrderBean.getPayStatus());
                statusVal = mOrderBean.getPayStatusId();

                twinklingLayout.startRefresh();

            }

            if (mTimePopWindow.isShowing()) {
                searchValue = "";
                mTimePopWindow.dismiss();
                txtTime.setText(mOrderBean.getPayStatus());
                startBtn.setText(mOrderBean.getStardtime());
                endBtn.setText(mOrderBean.getEndtime());
                twinklingLayout.startRefresh();


            }


        }
    };


    private OnItemClickListener mOnItemClickListener = new MyOnItemClickListener() {


        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            OrderQuiryTabeleBean.ListBean mitem = (OrderQuiryTabeleBean.ListBean) o;
            start(OrderQuiryDetailFragment.newInstance(mitem.getId() + "", "订单管理"), SINGLETASK);


        }
    };


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({pay_layout, R.id.ordier_layout, R.id.txt_time, R.id.start_time, R.id.end_time, R.id.search_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_btn:
                searchValueOrder();

                break;
            case R.id.start_time:
                String birthday = startBtn.getText().toString();

                DialogTool.getSingleton().showDatePicker(birthday, timeType, activity, mOnTimeSelectListener);
                break;
            case R.id.end_time:

                String endTime = endBtn.getText().toString();
                DialogTool.getSingleton().showDatePicker(endTime, timeType, activity, mEndSelectListener);

                break;

            case R.id.txt_time:
                mTimePopWindow.setWidth(popupWindowWith);
                mTimePopWindow.showAsDropDown(txtTime);

                break;
            case pay_layout:


                mSpinerPopWindow.setWidth(popupWindowWith);
                mSpinerPopWindow.showAsDropDown(payTage);
                if (mSpinerPopWindow.isShowing()) {
                    payLayout.setBackgroundColor(getResource().getColor(R.color.line));
                }
                break;
            case R.id.ordier_layout:  //全部订单状态
                Log.d("z", "onViewClicked: ");
                mOrderPopWindow.setWidth(popupWindowWith);
                mOrderPopWindow.showAsDropDown(ordierLayout);
                if (mOrderPopWindow.isShowing()) {
                    ordierLayout.setBackgroundColor(getResource().getColor(R.color.line));
                }
                break;
        }
    }

    private void searchValueOrder() {
        searchValue = getText(fragmentArriveShopSearch1Edit);
        if (!searchValue.isEmpty()) {
            hideSoftInput();
            twinklingLayout.startRefresh();
        }
    }


    private TimePickerView.OnTimeSelectListener mOnTimeSelectListener = new TimePickerView.OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {


            Date endData = MyDateUtils.stringDate(getText(endBtn), timeType);
            if (endData == null) {

            } else if (date.getTime() > endData.getTime()) {
                T.show("开始时间不能大于结束时间");
                return;
            }
            startBtn.setText(getTime(date, timeType));
            twinklingLayout.startRefresh();

        }
    };
    private TimePickerView.OnTimeSelectListener mEndSelectListener = new TimePickerView.OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            if (date == null) return;
            Date startData = MyDateUtils.stringDate(getText(startBtn), timeType);
            if (startData == null) {

            } else if (date.getTime() < startData.getTime()) {
                T.show("结束时间不能小于开始时间");
                return;
            }
            endBtn.setText(getTime(date, timeType));
            twinklingLayout.startRefresh();
        }
    };

    @Override
    public void getDataSuccess(List<OrderQuiryTabeleBean.ListBean> model, int total) {
        loadFinish = true;
        mPageWrapper.addDataSource(model, total);
    }


    @Override
    public void loadOrderInfoDestroy(String msg) {
        T.show(msg);
    }

    @Override
    public void loadAddRemark(String msg) {
        mitem.setRemark(mstrRemark);
        mOrderQuiryAdapter.notifyDataSetChanged();
        T.show(msg);
    }


    /**
     * 打印小票
     */
    @Override
    public void loadReceipt(final ReceiptBean mReceiptBean) {

        if (CheckUtils.isMIUIDevices()) {
            PrintMiuiHelper.receiptReceipt(MainActivity.getPrintService(), mReceiptBean);
        } else {
            PrinterReceipt mPrinterReceipt = PrinterReceipt.getInstance();
            final GpDevice mDevice = new GpDevice();
            mPrinterReceipt.printGp80(mReceiptBean, mDevice);
        }


    }

    @Override
    public void loadFail(String message) {
        T.show(message);
    }

    @Override
    public void updateFactorySucceed(OrderQuiryTabeleBean.ListBean mListItem) {
        mOrderQuiryAdapter.notifyDataSetChanged();
    }


}
